﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TjZheng.Core.Process.Handle;
using TjZheng.Framework;
using TjZheng.Web.Helper;
using TjZheng.WeiXin.Business;
using TjZheng.WeiXin.DataEntity;
using TjZheng.Cache;

namespace TjZheng.WeiXin.SDK.Pay
{
    public class NativePayServiceProcessHandle : ProcessHandle
    {
        /// <summary>
        /// 订单信息
        /// </summary>
        public OrderInfo OrderInfo { get; private set; }

        /// <summary>
        /// 检测商户系统回传的数据包
        /// </summary>
        /// <param name="objWeiXinPackage"></param>
        /// <returns></returns>
        public virtual InvokeResult CheckWeiXinPackage(WeiXinPackage objWeiXinPackage)
        {
            if (objWeiXinPackage == null)
            {
                throw new ArgumentException("objWeiXinPackage");
            }

            InvokeResult objInvokeResult = new InvokeResult();
            if (objWeiXinPackage == null)
            {
                objInvokeResult.ResultCode = "WeiXinPackageNotExist";
                objInvokeResult.ResultCode = "商户系统传来的微信数据包不存在";
                return objInvokeResult;
            }

            string signature = objWeiXinPackage.GetDictValue<string>("Signature");
            if (signature.IsNull())
            {
                objInvokeResult.ResultCode = "SignatureNotExist";
                objInvokeResult.ResultCode = "商户系统传来的微信数据包不存在Signature";
                return objInvokeResult;
            }

            int merchantId = objWeiXinPackage.GetDictValue<int>("MerchantId");
            if (merchantId <= 0)
            {
                objInvokeResult.ResultCode = "MerchantIdNotExist";
                objInvokeResult.ResultCode = "商户系统传来的微信数据包不存在MerchantId";
                return objInvokeResult;
            }

            string appId = objWeiXinPackage.GetDictValue<string>("AppId");
            if (appId.IsNull())
            {
                objInvokeResult.ResultCode = "AppIdNotExist";
                objInvokeResult.ResultCode = "商户系统传来的微信数据包不存在Signature";
                return objInvokeResult;
            }

            string mchId = objWeiXinPackage.GetDictValue<string>("MChId");
            if (appId.IsNull())
            {
                objInvokeResult.ResultCode = "MChIdNotExist";
                objInvokeResult.ResultCode = "商户系统传来的微信数据包不存在MChId";
                return objInvokeResult;
            }

            string version = objWeiXinPackage.GetDictValue<string>("Version");
            if (appId.IsNull())
            {
                objInvokeResult.ResultCode = "VersionNotExist";
                objInvokeResult.ResultCode = "商户系统传来的微信数据包不存在Version";
                return objInvokeResult;
            }

            string productId = objWeiXinPackage.GetDictValue<string>("ProductId");
            if (productId.IsNull())
            {
                objInvokeResult.ResultCode = "ProductIdNotExist";
                objInvokeResult.ResultCode = "商户系统传来的微信数据包不存在ProductId";
                return objInvokeResult;
            }

            string randomString = objWeiXinPackage.GetDictValue<string>("RandomString");
            if (randomString.IsNull())
            {
                objInvokeResult.ResultCode = "RandomStringNotExist";
                objInvokeResult.ResultCode = "商户系统传来的微信数据包不存在RandomString";
                return objInvokeResult;
            }

            string accessDomain = objWeiXinPackage.GetDictValue<string>("AccessDomain");
            if (randomString.IsNull())
            {
                objInvokeResult.ResultCode = "AccessDomainNotExist";
                objInvokeResult.ResultCode = "商户系统传来的微信数据包不存在AccessDomain";
                return objInvokeResult;
            }

            BizPayAuthorize objBizPayAuthorize = new BizPayAuthorize();
            PayAuthorize objPayAuthorize = objBizPayAuthorize.GetRecordCache("", TimeSpan.FromSeconds(30), "AppId=@AppId AND MChId=@MChId AND AccessDomain  like @AccessDomain AND Version=@Version", new { AppId = appId, MChId = mchId, AccessDomain = string.Format("{0}%", accessDomain), Version = version });
            if (objPayAuthorize == null)
            {
                objInvokeResult.ResultCode = "PayAuthorizeNotExist";
                objInvokeResult.ResultCode = "当前商户系统没有访问权限";
                return objInvokeResult;
            }

            string checkSignature = (merchantId + appId + mchId + version + productId + randomString + accessDomain).EncodeMD5(objPayAuthorize.AccessToken);
            if (signature != checkSignature)
            {
                objInvokeResult.ResultCode = "SignatureNotMatch";
                objInvokeResult.ResultCode = "商户系统传来的微信数据包签名不合法";
                return objInvokeResult;
            }
            objInvokeResult.Data = objPayAuthorize;
            return objInvokeResult;
        }

        /// <summary>
        /// 生成订单
        /// </summary>
        /// <param name="objWeiXinPackage"></param>
        public virtual void CreateOrderInfo(WeiXinPackage objWeiXinPackage)
        {
            if (objWeiXinPackage == null)
            {
                throw new ArgumentNullException("objWeiXinPackage");
            }

            OrderInfo objOrderInfo = new OrderInfo();

            string appId = objWeiXinPackage.GetDictValue<string>("AppId");

            string mchId = objWeiXinPackage.GetDictValue<string>("MChId");

            //商户订单号
            objOrderInfo.OutTradeNo = WxPayApi.GenerateOutTradeNo(mchId);
            ////微信支付单号
            //objOrderInfo.TransactionId = objProvide.TransactionId.CutWord(32, null);
            //订单标题
            objOrderInfo.OrderTitle = objWeiXinPackage.GetDictValue<string>("OrderTitle").CutWord(256, "");
            //订单附加数据
            objOrderInfo.OrderAttach = objWeiXinPackage.GetDictValue<string>("OrderAttach").CutWord(512, null);
            //订单内容
            objOrderInfo.OrderContent = objWeiXinPackage.GetDictValue<string>("OrderContent").CutWord(1024, null);
            //联系人名称
            objOrderInfo.ContactName = objWeiXinPackage.GetDictValue<string>("ContactName").CutWord(32, null);
            //联系人电话
            objOrderInfo.ContactPhone = objWeiXinPackage.GetDictValue<string>("ContactPhone").CutWord(32, null);
            //联系人送货地址
            objOrderInfo.ContactAddress = objWeiXinPackage.GetDictValue<string>("ContactAddress").CutWord(64, null);
            //联系人附加数据
            objOrderInfo.ContactAttach = objWeiXinPackage.GetDictValue<string>("ContactAttach").CutWord(512, null);
            //公众号标识
            objOrderInfo.AppId = appId;
            //商户号
            objOrderInfo.MChId = mchId;
            //订单金额
            objOrderInfo.TotalFee = objWeiXinPackage.GetDictValue<decimal>("TotalFee");
            //价格单位
            objOrderInfo.PriceUnit = objWeiXinPackage.GetDictValue<string>("PriceUnit").CutWord(16, "");
            //交易类型
            objOrderInfo.DealType = "NATIVE";
            //产品编号
            objOrderInfo.ProductId = objWeiXinPackage.GetDictValue<string>("ProductId").CutWord(32, null);
            //产品名称
            objOrderInfo.ProductName = objWeiXinPackage.GetDictValue<string>("ProductName").CutWord(64, null);
            //产品编码
            objOrderInfo.ProductCode = objWeiXinPackage.GetDictValue<string>("ProductCode").CutWord(32, null);
            //产品标签
            objOrderInfo.ProductTag = objWeiXinPackage.GetDictValue<string>("ProductTag").CutWord(128, null);
            //产品图片
            objOrderInfo.ProductImage = objWeiXinPackage.GetDictValue<string>("ProductImage").CutWord(256, null);
            //产品描述
            objOrderInfo.ProductDescription = objWeiXinPackage.GetDictValue<string>("ProductDescription").CutWord(512, null);
            //订单附加数据
            objOrderInfo.ProductAttach = objWeiXinPackage.GetDictValue<string>("ProductAttach").CutWord(512, null);
            //终端ip
            objOrderInfo.CreateIP = SystemWebAsset.GetServerIP();
            //订单来源
            objOrderInfo.FromSource = SystemWebAsset.GetClientIP();
            //订单创建时间
            objOrderInfo.CreateTime = DateTime.Now;
            //订单完成时间
            objOrderInfo.FinishTime = DateTime.MinValue;
            //订单过期时间
            objOrderInfo.ExpireTime = DateTime.Now.AddHours(2);
            //订单完成署名
            objOrderInfo.FinishSignName = null;
            //交易状态
            objOrderInfo.TradeStatus = 0;
            //订单状态
            objOrderInfo.OrderStatus = 0;
            //是否删除
            objOrderInfo.IsDelete = 0;
            //S1
            objOrderInfo.S1 = objWeiXinPackage.GetDictValue<string>("OrderAttach").CutWord(256, null);
            //S1
            objOrderInfo.S2 = objWeiXinPackage.GetDictValue<string>("OrderAttach").CutWord(256, null);
            //
            objOrderInfo.I1 = objWeiXinPackage.GetDictValue<int>("I1");
            //
            objOrderInfo.I2 = objWeiXinPackage.GetDictValue<int>("I2");

            BizOrderInfo objBizOrderInfo = new BizOrderInfo(mchId);//创建订单分表链接
            objBizOrderInfo.AddAsync(objOrderInfo);

            this.OrderInfo = objOrderInfo;
        }
    }
}
